﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TextAutoEdit
{
    public partial class MainForm : Form
    {

        private static readonly HttpClient client = new HttpClient();

        public static MainForm Instance { get; private set; }

        public MainForm()
        {
            Instance = this;
            InitializeComponent();
        }

        private void MLog_PrintEvent(string obj)
        {
            if (LogTB.InvokeRequired)
            {
                LogTB.Invoke(new Action<string>((msg) =>
                {
                    LogTB.Text = obj + "\r\n" + LogTB.Text;
                }), obj);
            }
            else
            {
                LogTB.Text = obj + "\r\n" + LogTB.Text;
            }
        }

        public void SetTBContent(string text)
        {
            if (TBContent.InvokeRequired)
            {
                TBContent.Invoke(new Action<string>((msg) =>
                {
                    TBContent.Text = text;
                }), text);
            }
            else
            {
                TBContent.Text = text;
            }
        }

        private async void Edit_Click(object sender, EventArgs e)
        {
            Edit.Enabled = false;
            object[] rets = await MLua.ExFuncAsync("EditString", TBContent.Text);

            Edit.Enabled = true;
            if (rets==null || rets.Length <= 0) return;
            TBContent.Text = (string)rets[0];
        }

        private async void ReloadScriptBtn_Click(object sender, EventArgs e)
        {
            await MLua.ReloadAsync();
        }

        private async void TranslateBtn_Click(object sender, EventArgs e)
        {
            TranslateBtn.Enabled = false;

            string s = await client.GetStringAsync("https:" + $"//translate.googleapis.com/translate_a/single?client=gtx&dt=t&sl=en&tl=zh-CN&q={TBContent.Text}");

            object[] rets = await MLua.ExFuncAsync("ParserJsonToString", s);
            TranslateBtn.Enabled = true;

            if (rets == null) return;

            TBContent.Text = (string)rets[0];

            MLog.Log("翻译完成");
        }

        private void TBContent_TextChanged(object sender, EventArgs e)
        {

        }

        private async void MainForm_Load(object sender, EventArgs e)
        {
            MLog.PrintEvent += MLog_PrintEvent;
            await MLuaEvn.InitAsync(GetType().Assembly);
            MLog.Log("初始化完成！");
        }
    }
}
